package com.cyzy.server.service.impl;

import com.cyzy.common.constant.MessageConstant;
import com.cyzy.common.constant.StatusConstant;
import com.cyzy.common.exception.AccountLockedException;
import com.cyzy.common.exception.AccountNotFoundException;
import com.cyzy.common.exception.PasswordErrorException;
import com.cyzy.pojo.dto.SuperintendentDTO;
import com.cyzy.pojo.dto.SuperintendentLoginDTO;
import com.cyzy.pojo.entity.Superintendent;
import com.cyzy.server.dao.SuperintendentDao;
import com.cyzy.server.service.SuperintendentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.security.MessageDigest;

@Service
public class SuperintendentServiceImpl implements SuperintendentService {

    @Autowired
    private SuperintendentDao superintendentDao;

    /**
     * 管理者注册
     *
     * @param superintendentDTO
     * @return
     */
    @Override
    public void register(SuperintendentDTO superintendentDTO) {
        String password = superintendentDTO.getPassword();

        Superintendent superintendent = new Superintendent();

        //对象拷贝
        BeanUtils.copyProperties(superintendentDTO, superintendent);

        //设置账号的状态 默认正常 1正常 0锁定
        superintendent.setStatus(StatusConstant.ENABLE);

        //密码用md5加密
        superintendent.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));

        superintendentDao.insert(superintendent);
    }

    /**
     * 管理者登录
     *
     * @param superintendentLoginDTO
     * @return
     */
    @Override
    public Superintendent login(SuperintendentLoginDTO superintendentLoginDTO) {
        String studentId = superintendentLoginDTO.getStudentId();
        String password = superintendentLoginDTO.getPassword();

        //根据学号查询出数据库中的数据
        Superintendent superintendent = superintendentDao.getByStudentId(studentId);

        //处理异常情况
        if (superintendent == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传过来的明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(superintendent.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (superintendent.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return superintendent;

    }
}
